package fun.flyee.android.pengshan.acts.helper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSONObject;

import java.io.File;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import fun.flyee.android.pengshan.api.ApiClient;
import fun.flyee.android.pengshan.models.Version;
import fun.flyee.android.pengshan.utils.Systems;
import fun.flyee.pengshan.social.BuildConfig;

public class ApkHelper {

    private File apk;
    private Version version;

    private Activity mActivity;

    public ApkHelper(Activity act) {
        this.mActivity = act;
    }

    public void checkVersion() {
        ApiClient.checkVersion((result) -> {
            if (result.code == 200 && result.data != null && result.data.toString().length() > 0) {
                version = JSONObject.parseObject(result.data.toString(), Version.class);
                mActivity.runOnUiThread(() -> {
                    if ((BuildConfig.VERSION_CODE + "").equals(version.version)) return;
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                            .setCancelable(false)
                            .setTitle("发现新版本")
                            .setMessage("更新内容：" + version.updateContent)
                            .setPositiveButton("立即更新", (dialog, i) -> {
                                dialog.dismiss();
                                download(version);
                            });
                    if ("0".equals(version.forceUpdate)) {
                        builder.setNegativeButton("下次再说", (dialog, i) -> {
                            dialog.dismiss();
                        });
                    }
                    try {
                        builder.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    private void download(Version version) {
        File apkFolder = new File(mActivity.getFilesDir(), "apks");
        if (!apkFolder.exists()) {
            apkFolder.mkdir();
        }
        apk = new File(apkFolder, version.fileName + ".apk");
        if (apk.exists()) {
            install(apk);
        } else {
            apk = new File(apkFolder, version.fileName + ".tmp");
            ProgressDialog progressDialog = new ProgressDialog(mActivity);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setTitle("正在下载：" + version.fileName);
            progressDialog.setMax(100);
            progressDialog.setProgress(0);
            progressDialog.setCancelable(false);
            progressDialog.show();
            Handler installHandler = new Handler() {
                public void handleMessage(Message msg) {
                    progressDialog.dismiss();
                    install(apk);
                }
            };
            Handler downloadHandler = new Handler() {
                public void handleMessage(Message msg) {
                    if (msg.what == 200) {
                        apk = renameFile(apk);
                        installHandler.sendEmptyMessageDelayed(0, 500);
                    } else {
                        progressDialog.dismiss();
                        retry(msg.obj.toString(), version);
                    }
                }
            };
            ApiClient.download(version.fileUrl, apk, (progress) -> {
                mActivity.runOnUiThread(() -> progressDialog.setProgress(progress));
            }, (result -> {
                mActivity.runOnUiThread(() -> {
                    Message msg = downloadHandler.obtainMessage(result.code, result.msg);
                    downloadHandler.sendMessageDelayed(msg, 500);
                });
            }));
        }
    }

    private File renameFile(File src) {
        File dst = new File(src.getAbsolutePath().replaceAll("tmp", "apk"));
        src.renameTo(dst);
        return dst;
    }

    private void retry(String msg, Version version) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                .setCancelable(false)
                .setTitle(msg)
                .setMessage("是否重试下载？")
                .setPositiveButton("是", (dialog, i) -> {
                    dialog.dismiss();
                    if (apk.exists()) {
                        apk.delete();
                    }
                    download(version);
                })
                .setNegativeButton("否", (dialog, i) -> {
                    dialog.dismiss();
                    if ("1".equals(version.forceUpdate)) {
                        mActivity.finish();
                    }
                });
        builder.show();
    }

    public void install() {
        install(apk);
    }

    private void install(File apk) {
        if (Systems.requestInstallPermission(mActivity)) return;
        if (version.forceUpdate.equals("1")) {
            new AlertDialog.Builder(mActivity)
                    .setCancelable(false)
                    .setTitle("版本更新")
                    .setMessage("应用安装中")
                    .setPositiveButton("退出应用", (dialog, i) -> {
                        dialog.dismiss();
                        mActivity.finish();
                    });
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mActivity, mActivity.getPackageName() + ".fileprovider", apk);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(apk);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        mActivity.startActivity(intent);
    }

}
